'use client';

import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Tabs, Table, Button, Tag, Space, message, Input, Select, DatePicker } from 'antd';
import { DownloadOutlined, DeleteOutlined, InfoCircleOutlined, SearchOutlined, FilterOutlined, ReloadOutlined } from '@ant-design/icons';
import AdminLayout from '../AdminLayout';
import ModelDetailModal from './components/ModelDetailModal';

const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

// 模拟本地已安装模型数据
const localModelsData = [
  {
    key: '1',
    name: 'Stable Diffusion v1.5',
    type: '文生图',
    size: '4.27GB',
    lastUsed: '2023-12-15',
    status: '已安装',
  },
  {
    key: '2',
    name: 'Midjourney v5',
    type: '文生图',
    size: '7.82GB',
    lastUsed: '2023-12-20',
    status: '已安装',
  },
  {
    key: '3',
    name: 'ControlNet v1.1',
    type: '控制模型',
    size: '1.25GB',
    lastUsed: '2023-12-18',
    status: '已安装',
  },
  {
    key: '4',
    name: 'DALL-E 3',
    type: '文生图',
    size: '6.54GB',
    lastUsed: '2023-12-10',
    status: '已安装',
  },
];

const ModelManagement: React.FC = () => {
  const [activeTab, setActiveTab] = useState('local');
  const [downloadableModels, setDownloadableModels] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedModel, setSelectedModel] = useState<any>(null);
  const [isLocalModel, setIsLocalModel] = useState(true);
  
  // 搜索和过滤状态
  const [searchText, setSearchText] = useState('');
  const [filteredLocalModels, setFilteredLocalModels] = useState(localModelsData);
  const [filteredDownloadableModels, setFilteredDownloadableModels] = useState<any[]>([]);
  const [typeFilter, setTypeFilter] = useState<string>('all');
  
  // 获取可下载模型数据
  useEffect(() => {
    if (activeTab === 'downloadable') {
      fetchDownloadableModels();
    }
  }, [activeTab]);
  
  // 当搜索文本或类型过滤器改变时，过滤本地模型
  useEffect(() => {
    const filtered = localModelsData.filter(model => {
      const matchesSearch = model.name.toLowerCase().includes(searchText.toLowerCase());
      const matchesType = typeFilter === 'all' || model.type === typeFilter;
      return matchesSearch && matchesType;
    });
    setFilteredLocalModels(filtered);
  }, [searchText, typeFilter]);
  
  // 当搜索文本改变时，过滤可下载模型
  useEffect(() => {
    if (downloadableModels.length > 0) {
      const filtered = downloadableModels.filter(model => 
        model.name.toLowerCase().includes(searchText.toLowerCase()) ||
        model.description.toLowerCase().includes(searchText.toLowerCase())
      );
      setFilteredDownloadableModels(filtered);
    }
  }, [searchText, downloadableModels]);

  const fetchDownloadableModels = async () => {
    setLoading(true);
    try {
      const response = await fetch('https://extension-list.oystermercury.top/automatic.json');
      const data = await response.json();
      
      // 转换API数据为表格所需格式
      const formattedData = data.extensions.map((item: any, index: number) => ({
        key: index.toString(),
        name: item.name,
        description: item.description || '无描述',
        tags: item.tags || [],
        stars: item.stars || 0,
        url: item.url,
      }));
      
      setDownloadableModels(formattedData);
      setFilteredDownloadableModels(formattedData);
    } catch (error) {
      console.error('获取可下载模型失败:', error);
      message.error('获取可下载模型列表失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 显示模型详情
  const showModelDetail = (record: any, isLocal: boolean) => {
    setSelectedModel(record);
    setIsLocalModel(isLocal);
    setDetailModalVisible(true);
  };

  // 下载模型
  const handleDownloadModel = (record: any) => {
    message.loading(`正在下载模型: ${record.name}`, 2.5)
      .then(() => message.success(`模型 ${record.name} 下载成功！`, 2));
  };

  // 删除模型
  const handleDeleteModel = (record: any) => {
    message.loading(`正在删除模型: ${record.name}`, 1.5)
      .then(() => message.success(`模型 ${record.name} 已成功删除`, 2));
  };
  
  // 重置过滤器
  const resetFilters = () => {
    setSearchText('');
    setTypeFilter('all');
  };

  // 本地模型表格列定义
  const localColumns = [
    {
      title: '模型名称',
      dataIndex: 'name',
      key: 'name',
      sorter: (a: any, b: any) => a.name.localeCompare(b.name),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      filters: [
        { text: '文生图', value: '文生图' },
        { text: '控制模型', value: '控制模型' },
      ],
      onFilter: (value: string, record: any) => record.type === value,
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      sorter: (a: any, b: any) => {
        const sizeA = parseFloat(a.size.replace('GB', ''));
        const sizeB = parseFloat(b.size.replace('GB', ''));
        return sizeA - sizeB;
      },
    },
    {
      title: '最后使用时间',
      dataIndex: 'lastUsed',
      key: 'lastUsed',
      sorter: (a: any, b: any) => new Date(a.lastUsed).getTime() - new Date(b.lastUsed).getTime(),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text: string) => (
        <Tag color="green">{text}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<InfoCircleOutlined />}
            onClick={() => showModelDetail(record, true)}
          >
            详情
          </Button>
          <Button 
            type="text" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteModel(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 可下载模型表格列定义
  const downloadableColumns = [
    {
      title: '模型名称',
      dataIndex: 'name',
      key: 'name',
      sorter: (a: any, b: any) => a.name.localeCompare(b.name),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      render: (tags: string[]) => (
        <>
          {tags.map(tag => (
            <Tag color="blue" key={tag}>
              {tag}
            </Tag>
          ))}
        </>
      ),
      filters: [
        { text: 'script', value: 'script' },
        { text: 'tab', value: 'tab' },
        { text: 'UI related', value: 'UI related' },
        { text: 'editing', value: 'editing' },
        { text: 'animation', value: 'animation' },
      ],
      onFilter: (value: string, record: any) => record.tags.includes(value),
    },
    {
      title: '星标数',
      dataIndex: 'stars',
      key: 'stars',
      sorter: (a: any, b: any) => a.stars - b.stars,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space>
          <Button 
            type="primary" 
            icon={<DownloadOutlined />}
            onClick={() => handleDownloadModel(record)}
          >
            下载
          </Button>
          <Button 
            type="text" 
            icon={<InfoCircleOutlined />}
            onClick={() => showModelDetail(record, false)}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ];

  // 搜索和过滤器区域
  const renderFilterArea = () => (
    <Row gutter={16} style={{ marginBottom: 16 }}>
      <Col xs={24} sm={12} md={8} lg={6}>
        <Search
          placeholder="搜索模型名称"
          value={searchText}
          onChange={e => setSearchText(e.target.value)}
          allowClear
        />
      </Col>
      {activeTab === 'local' && (
        <Col xs={24} sm={12} md={8} lg={6}>
          <Select 
            style={{ width: '100%' }} 
            placeholder="按类型筛选"
            value={typeFilter}
            onChange={value => setTypeFilter(value)}
          >
            <Option value="all">全部类型</Option>
            <Option value="文生图">文生图</Option>
            <Option value="控制模型">控制模型</Option>
          </Select>
        </Col>
      )}
      <Col xs={24} sm={12} md={8} lg={6}>
        <Button 
          icon={<ReloadOutlined />} 
          onClick={resetFilters}
        >
          重置筛选
        </Button>
      </Col>
    </Row>
  );

  return (
    <AdminLayout pageTitle="模型管理">
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card>
            <Tabs 
              activeKey={activeTab} 
              onChange={setActiveTab}
              type="card"
              size="large"
              items={[
                {
                  key: 'local',
                  label: '本地已安装模型',
                  children: (
                    <>
                      {renderFilterArea()}
                      <Table 
                        columns={localColumns} 
                        dataSource={filteredLocalModels} 
                        pagination={{ pageSize: 10 }}
                        rowKey="key"
                      />
                    </>
                  )
                },
                {
                  key: 'downloadable',
                  label: '可下载模型',
                  children: (
                    <>
                      {renderFilterArea()}
                      <Table 
                        columns={downloadableColumns} 
                        dataSource={filteredDownloadableModels} 
                        pagination={{ pageSize: 10 }}
                        loading={loading}
                        rowKey="key"
                      />
                    </>
                  )
                }
              ]}
            />
          </Card>
        </Col>
      </Row>

      {/* 模型详情对话框 */}
      <ModelDetailModal
        visible={detailModalVisible}
        onClose={() => setDetailModalVisible(false)}
        model={selectedModel}
        isLocalModel={isLocalModel}
      />
    </AdminLayout>
  );
};

export default ModelManagement; 